package com.ufgov.agcfs.baseData.service;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.persistence.SearchFilter;

import com.ufgov.agcfs.baseData.dao.CritAccDao;
import com.ufgov.agcfs.baseData.entity.CritAcc;

import com.ufgov.agcfs.pub.UUID;


@Service
@Transactional(propagation = Propagation.REQUIRES_NEW)
public class CritAccService {

	@Autowired
	public CritAccDao critAccDao;
	
	
	public List<CritAcc> getAccList(){
		return critAccDao.getAccList();
	}
	
//	public List<AccNode> getRptTypeByND(String nd){
//		List<AccNode> nodes = new ArrayList<RptTypeNode>();
//		List<CritAcc> reportTypeList = reportTypeDao.findAllReportType();
//		for (ReportType reportType : reportTypeList) {
//			if (reportType.getNd().equals(nd)){
//				RptTypeNode node = RptTypeNode.createNode(nd+reportType.getReportType(), reportType.getNd(),
//						reportType.getReportType(),reportType.getReportTypeName(), false, nd, "child");
//				nodes.add(node);
//			}
//		}
//		return nodes;
//	}
	
	public List<CritAcc> searchCritAcc(Map<String, Object> searchParams) {
		
		Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
		CritAcc critAcc = new CritAcc();
		
		SearchFilter searchFilternd =filters.get("EQ_nd");
		String nd = "";
		if (searchFilternd!=null) {
			nd = (String) searchFilternd.value;
			critAcc.setNd(nd);
		}	
		SearchFilter searchFilteraccBookTypeCode =filters.get("EQ_accBookTypeCode");
		String accBookTypeCode = "";
		if (searchFilteraccBookTypeCode!=null) {
			accBookTypeCode = (String) searchFilteraccBookTypeCode.value;
			critAcc.setAccBookTypeCode(accBookTypeCode);
		}
		SearchFilter searchFilteraccNo =filters.get("EQ_accNo");
		String accNo = "";
		if (searchFilteraccNo!=null) {
			accNo = (String) searchFilteraccNo.value;
			critAcc.setAccNo(accNo);
		}
		
		return critAccDao.searchCritAcc(critAcc);
		
	}
	
	public void saveCritAcc(CritAcc critAcc,Map<String, String> resultMap){
		if ((critAcc.getId().equals(""))||(critAcc.getId()==null)) {
			CritAcc critAccSearch= critAccDao.searchCritAccHas(critAcc);
			if (critAccSearch!=null){
				getErrorMsg(resultMap,"saveError","系统中已存在相同会计科目！");
				return;
			}
			critAcc.setId(UUID.randomUUID().toString());
			critAccDao.insertCritAcc(critAcc);
		} else {
			critAccDao.updateCritAcc(critAcc);
		}	
	}

	private void getErrorMsg(Map<String, String> resultMap,String flg, String reason) {
		resultMap.put("result", "fail");
		resultMap.put(flg, reason);
		resultMap.put("reason", "保存失败！");
	}
	
	public void updateCritAcc(CritAcc critAcc){
		critAccDao.updateCritAcc(critAcc);
	}
}
